package com.apotik.legenda.frameinternal;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.apotik.legenda.custom.TableModelCustom;
import com.apotik.legenda.dao.UserDao;
import com.apotik.legenda.dialog.AddEditUserDialog;
import com.apotik.legenda.model.User;
import com.apotik.legenda.observer.GeneralObserver;
import com.apotik.legenda.util.AppUtil;

import java.awt.Font;

public class UserInternalFrame extends JInternalFrame implements ActionListener, GeneralObserver  {
	private static final long serialVersionUID = 1L;

	private JButton btnAdd;
	private JButton btnEdit;
	private JButton btnDelete;
	private JButton btnRefresh;
	private JButton btnDetail;
	
	private TableModelCustom tableModel;
	private JTable table;
	private AddEditUserDialog addEditUserDialog;
	
	private User user;
	private int modelRow  = -1;
	private JTextField textFieldSearch;
	private JPanel panel;
	
	public UserInternalFrame(User user) {
		super("User", true, true, true, true);
		
		this.user = user;
		
		setSize(1000, 500);
		setVisible(true);
		
		JPanel northPanel = new JPanel();
		northPanel.setLayout(new BorderLayout());
		getContentPane().add(northPanel, BorderLayout.NORTH);
		
		JPanel headPanel = new JPanel();
		headPanel.setLayout(new BorderLayout());
		northPanel.add(headPanel, BorderLayout.NORTH);
		
		JPanel btns1Panel = new JPanel();
		btns1Panel.setLayout(new FlowLayout());
		headPanel.add(btns1Panel, BorderLayout.WEST);
		
		btnAdd = new JButton("Tambah");
		btnAdd.addActionListener(this);
		btnAdd.setMnemonic(KeyEvent.VK_N);
		btnAdd.setToolTipText("ALT + N");
		btns1Panel.add(btnAdd);
		
		btnEdit = new JButton("Edit");
		btnEdit.addActionListener(this);
		btns1Panel.add(btnEdit);
		
		btnDelete = new JButton("Delete");
		btnDelete.addActionListener(this);
		btns1Panel.add(btnDelete);
		
		btnRefresh = new JButton("Refresh");
		btnRefresh.addActionListener(this);
		btns1Panel.add(btnRefresh);
		
		btnDetail = new JButton("Detail");
		btnDetail.addActionListener(this);
		btns1Panel.add(btnDetail);
		
		textFieldSearch = new JTextField();
		textFieldSearch.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
		        if (e.getKeyCode()==KeyEvent.VK_ENTER){
		        	loadDataTable();
		        }
			}
			@Override
			public void keyTyped(KeyEvent arg0) {}
		});
		headPanel.add(textFieldSearch, BorderLayout.EAST);
		textFieldSearch.setColumns(25);
		
		JLabel lblCariNama = new JLabel("Cari Username / Nama Lengkap : ");
		lblCariNama.setHorizontalAlignment(SwingConstants.RIGHT);
		headPanel.add(lblCariNama, BorderLayout.CENTER);
		
		/*JPanel btns2Panel = new JPanel();
		btns2Panel.setLayout(new FlowLayout());
		headPanel.add(btns2Panel, BorderLayout.EAST);
		
		searchField = new JTextField();
		searchField.setColumns(14);
		btns2Panel.add(searchField);*/
		
		JSeparator separator = new JSeparator();
		northPanel.add(separator, BorderLayout.SOUTH);
		
		
		
		JScrollPane scrollPane = new JScrollPane();
		getContentPane().add(scrollPane, BorderLayout.CENTER);
		
		String[] columnNames = {"Nama Lengkap", "Handphone", "Role", "Status"};
		tableModel = new TableModelCustom(columnNames);
		loadDataTable();
		
		table = new JTable();
		table.setModel(tableModel);
		table.setEnabled(true);
		table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
			@Override
			public void valueChanged(ListSelectionEvent arg0) {
				int viewRow = table.getSelectedRow();
				if(viewRow>-1){
					modelRow = table.convertRowIndexToModel(viewRow);
				}
			}
		});
		scrollPane.setViewportView(table);
		
		panel = southPanel();
		getContentPane().add(panel, BorderLayout.SOUTH);
	}
	
	private JPanel southPanel(){
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel panel_1 = new JPanel();
		panel.add(panel_1, BorderLayout.EAST);
		
		JButton btnBackPage = new JButton("< Back");
		btnBackPage.setFont(new Font("Tahoma", Font.PLAIN, 10));
		panel_1.add(btnBackPage);
		
		JButton btnNextPage = new JButton("Next >");
		btnNextPage.setFont(new Font("Tahoma", Font.PLAIN, 10));
		panel_1.add(btnNextPage);
		
		
		return panel;
	}
	
	@Override
	public void actionPerformed(ActionEvent ae) {
		Object obj =  ae.getSource();
		
		if(obj==btnAdd){
			addNew();
		}else if(obj==btnEdit){
			editDetailItem("Edit");
		}else if(obj==btnDelete){
			deleteItem();
		}else if(obj==btnRefresh){
			deleteAllTableRow();
			loadDataTable();
		}else if(obj==btnDetail){
			editDetailItem("Detail");
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void loadDataTable(){
		UserDao dao = new UserDao();
		List<User> list = dao.search(textFieldSearch.getText());
		if(list.size()>0){
			 deleteAllTableRow();
			 for(User d: list){
				 Vector v = new Vector();
				 v.add(d.getFullName());
				 v.add(d.getPhoneNumber()!=null ? d.getPhoneNumber():"");
				 v.add(d.getRole()!=null ? d.getRole().getRoleName():"Not set");
				 v.add(d.isActive()?"Aktif":"Tidak Aktif");
				 v.add(d);
				 if(d.getRole().getRoleCode().equalsIgnoreCase(AppUtil.ROLE_SUPER_ADMIN)){
					 if(this.user.getRole().getRoleCode().equalsIgnoreCase(AppUtil.ROLE_SUPER_ADMIN)){
						 tableModel.insertData(v); 
					 }
				 }else{
					 tableModel.insertData(v); 
				 }
			 }
		}   
	}
	
	@SuppressWarnings("rawtypes")
	private User selectedModel(){
		User user = null;
		if(modelRow!=-1){
			Vector v = (Vector) tableModel.getRowVector().get(modelRow);
			if(v!=null){
				user = (User) v.get(v.size()-1);
				if(user!=null){
					//System.out.println("OO: "+doctor.getDoctorId());
				}
			}
		}
		return user;
	}
	
	private void addNew(){
		boolean isVisible = false;
		if(addEditUserDialog!=null){
			isVisible = addEditUserDialog.isVisible();
		}
		
		if(isVisible){
			addEditUserDialog.toFront();
			addEditUserDialog.requestFocus();
		}else{
			addEditUserDialog = new AddEditUserDialog(this);
			addEditUserDialog.setVisible(true);
			addEditUserDialog.requestFocus();
		}
	}
	
	private void editDetailItem(String actFor){
		if(selectedModel()!=null){
			boolean isVisible = false;
			if(addEditUserDialog!=null){
				isVisible = addEditUserDialog.isVisible();
			}
			
			if(isVisible){
				addEditUserDialog.toFront();
				addEditUserDialog.requestFocus();
			}else{
				addEditUserDialog = new AddEditUserDialog(this);
				addEditUserDialog.setVisible(true);
				addEditUserDialog.requestFocus();
			}
			
			if(actFor.equalsIgnoreCase("Edit")){
				addEditUserDialog.editItem(selectedModel());
			}else if(actFor.equalsIgnoreCase("Detail")){
				addEditUserDialog.detail(selectedModel());
			}
		}else{
			JOptionPane.showMessageDialog(null, "Silahkan Pilih Item", "Exception", JOptionPane.ERROR_MESSAGE);
		}
		
	}
	
	private void deleteItem(){
		if(selectedModel()!=null){
			int result = JOptionPane.showConfirmDialog(null, "Apakah Anda yakin ingin menghapusnya?", "Question", JOptionPane.YES_NO_OPTION);
			if(result==JOptionPane.YES_OPTION){
				UserDao dao = new UserDao();
				boolean isSucces = dao.delete(selectedModel());
				if(isSucces){
					tableModel.removeRow(modelRow);
				}
			}
		}else{
			JOptionPane.showMessageDialog(null, "Silahkan Pilih Row Table", "Exception", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	private void deleteAllTableRow(){
		tableModel.removeRowAll();
	}

	@Override
	public void response(HashMap<String, Object> hm) {
		try {
			loadDataTable();
		} catch (Exception e) {
			//JOptionPane.showMessageDialog(null, "Silahkan Pilih Row Table", "Exception", JOptionPane.ERROR_MESSAGE);
		}
	}
}